package com.tjjingpan.filepersistencetest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val inputText = load()
        if(inputText.isNotEmpty())
        {
            editText.setText(inputText)
            editText.setSelection(inputText.length)
            Toast.makeText(this,"Restoring succeeded",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val inputText = editText.text.toString()
        save(inputText)
    }
    private fun save(inputTesxt:String)
    {
        try{
            val output = openFileOutput("data", Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            writer.use {
                it.write(inputTesxt)
            }
        }
        catch(e:IOException)
        {
            e.printStackTrace()
        }
    }

    private fun load():String{
        val conent = StringBuilder()
        try {
            val input= openFileInput("data")
            val reader = BufferedReader(InputStreamReader(input))
            reader.use{
                reader.forEachLine {
                    conent.append(it)
                }
            }
        }catch (e:IOException){
            e.printStackTrace()
        }
        return conent.toString()
    }
}